from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT
import json

from utils.report.base import create_table, set_cell_border, delete_table_first_row, delete_table_first_last_row


def generate_report(data, document, table_count):
    # 根据状态判断是否需要生成对应的报告
    # 生成频数结果
    fre_arr = data.get('frequency_analysis')
    frequency_report(document, fre_arr, table_count)  # 对象和当前有几个表格
    # 生成信度分析结果
    reliability_analysis_obj = data.get('reliability_analysis')
    re_report(document, reliability_analysis_obj, table_count)
    # 生成效度分析结果
    va_obj = data.get('validity_analysis')
    va_report(va_obj, document, table_count)
    # 相关
    co_arr = data.get('correlation_analysis')
    co_report(co_arr, document, table_count)
    # 回归
    regressive_obj = data.get('regressive_analysis')
    regressive_report(regressive_obj, document, table_count)


def va_report(va_obj, document, table_count):
    # 增加标题
    title1 = document.add_heading(level=1)
    t1_run = title1.add_run('效度及因子分析')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)
    # 生成表1及描述信息
    generate_va_table1(document, table_count, va_obj)
    # 生成表2及描述信息
    table2_param = va_obj.get('total_variance_explanation')
    generate_va_table2(document, table_count, table2_param)
    # 生成表3及描述信息
    generate_va_table3(document, table_count, va_obj)
    return


def generate_va_table1(document, table_count, va_obj):
    # 新建表格
    init_rows = 5
    init_cols = 3
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(document, init_rows, init_cols)
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + "KMO 和 Bartlett 的检验"
    table.cell(1, 0).merge(table.cell(1, 1))
    # table.cell(2, 0).merge(table.cell(3, 0)).merge(table.cell(4, 0))
    # 赋值
    table.cell(1, 0).text = "KMO 值"
    table.cell(2, 0).text = "Bartlett 球形度检验"
    table.cell(2, 1).text = "近似卡方"
    table.cell(3, 1).text = "df"
    table.cell(4, 1).text = "p值"
    first_table_obj = va_obj.get('kmo_bartlett')
    kmo_value = convert_str_to_float_3(first_table_obj.get('kmo'))
    table.cell(1, init_cols - 1).text = kmo_value
    table.cell(2, init_cols - 1).text = convert_str_to_float_3(first_table_obj.get('bartlett').get('square'))
    table.cell(3, init_cols - 1).text = convert_str_to_float_3(first_table_obj.get('bartlett').get('dof'))
    table.cell(4, init_cols - 1).text = convert_str_to_float_3(first_table_obj.get('bartlett').get('p_value'))
    # 修改表格格式
    delete_table_first_row(table)
    set_cell_border(table.cell(1, 0), top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(1, 1), top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(1, 2), top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(2, 0), top={"sz": 4, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(2, 1), top={"sz": 4, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(2, 2), top={"sz": 4, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(4, 0), bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(4, 1), bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    set_cell_border(table.cell(4, 2), bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    # 插入描述信息
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    describe = ("使用因子分析进行信息浓缩研究，首先分析研究数据是否适合进行因子分析，从上表可以看出：KMO 为 " + kmo_value +
                "，大于 0.6，满足因子分析的前提要求，意味着数据可用于因子分析研究。以及数据通过 Bartlett 球形度检验(p<0.05)，说明研究数据适合进行因子分析。")
    paragraph.add_run(describe)
    # 格式化表格
    format_table(table)


def generate_va_table2(document, table_count, datas):
    """
    生成表2
    :param init_cols: 初始化列
    :param table: 当前这个表
    :param table_count: 当前这个表是整个word中的第几个表
    :param datas: 需要处理的对象-数据
    :return:
    """
    init_rows = 3
    init_cols = 10
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(document, init_rows, init_cols)
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + "KMO 和 Bartlett 的检验"
    # 表2第一行表头
    table.cell(1, 0).merge(table.cell(2, 0))
    table.cell(1, 0).text = "因子编号"
    table.cell(1, 1).merge(table.cell(1, 2)).merge(table.cell(1, 3))
    table.cell(1, 1).text = "特征根"
    table.cell(1, 4).merge(table.cell(1, 5)).merge(table.cell(1, 6))
    table.cell(1, 4).text = "旋转前方差解释率"
    table.cell(1, 7).merge(table.cell(1, 8)).merge(table.cell(1, 9))
    table.cell(1, 7).text = "旋转后方差解释率"
    table.cell(1, 1).text = "特征根"
    # 表2第二行表头
    table.cell(2, 1).text = "特征根"
    table.cell(2, 2).text = "方差解释率%"
    table.cell(2, 3).text = "累计%"
    table.cell(2, 4).text = "特征根"
    table.cell(2, 5).text = "方差解释率%"
    table.cell(2, 6).text = "累计%"
    table.cell(2, 7).text = "特征根"
    table.cell(2, 8).text = "方差解释率%"
    table.cell(2, 9).text = "累计%"
    # 动态添加数据
    describe_arr = []
    after_max = ''
    factor_counts = 0
    # 生成表格内容
    for i in range(len(datas)):
        cor_o = datas[i]
        table.add_row()
        cur_row = table.rows[-1]
        cur_row.cells[0].text = str(i + 1)
        cur_row.cells[1].text = convert_str_to_float_3(cor_o.get('values').get('0'))
        cur_row.cells[2].text = convert_str_to_float_3_persent(cor_o.get('values').get('1'))
        cur_row.cells[3].text = convert_str_to_float_3_persent(cor_o.get('values').get('2'))
        cur_row.cells[4].text = convert_str_to_float_3(cor_o.get('values').get('3'))
        cur_row.cells[5].text = convert_str_to_float_3_persent(cor_o.get('values').get('4'))
        cur_row.cells[6].text = convert_str_to_float_3_persent(cor_o.get('values').get('5'))
        cur_row.cells[7].text = convert_str_to_float_3(cor_o.get('values').get('6'))
        a7 = convert_str_to_float_3_persent(cor_o.get('values').get('7'))
        cur_row.cells[8].text = a7
        if a7:
            factor_counts += 1
            describe_arr.append(a7)
        a8 = convert_str_to_float_3_persent(cor_o.get('values').get('8'))
        cur_row.cells[9].text = a8
        after_max = a8 or after_max
    # 生成正文内容
    describe = "上表格针对因子提取情况，以及因子提取信息量情况进行分析，从上表可知：因子分析一共提取出 "
    describe += str(factor_counts)
    describe += "个因子，特征根值均大于 1，此 "
    describe += str(factor_counts)
    describe += "个因子旋转后的方差解释率分别是"
    for i in describe_arr:
        describe += i + "%"
    describe += "旋转后累积方差解释率为" + after_max + "%。"
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    paragraph.add_run(describe)
    # 格式化表格
    format_table(table)
    add_three_lines_table_kmo(table)
    return


def add_three_lines_table_kmo(table):
    delete_table_first_last_row(table)
    first_row = table.rows[0]
    second_row = table.rows[3]
    for cell in first_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, top={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def generate_va_table3(document, table_count, datas):
    """
    生成表2
    :param document: word文档
    :param table_count: 当前这个表是整个word中的第几个表
    :param datas: 需要处理的对象-数据
    :return:
    """
    component_matrix = datas.get('component_matrix')  # 旋转后成分矩阵
    communalities = datas.get('communalities')  # 公因子方差
    if not component_matrix or not communalities:
        return
    dynamic_cols = len(component_matrix[0].get('values'))
    init_rows = 3
    init_cols = 2 + dynamic_cols
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(document, init_rows, init_cols)
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + "旋转后因子载荷系数表格"
    # 所有表头
    table.cell(1, 0).merge(table.cell(2, 0))
    table.cell(1, 0).text = "名称"
    base_merge_cell = table.cell(1, 1)
    for i in range(dynamic_cols):  # 合并单元格
        base_merge_cell.merge(table.cell(1, i + 1))
        table.cell(2, i + 1).text = "因子" + str(i + 1)
    table.cell(1, 1).text = "因子载荷系数"
    table.cell(1, init_cols - 1).merge(table.cell(2, init_cols - 1))
    table.cell(1, init_cols - 1).text = "共同度(公因子方差)"
    # 动态添加数据
    for i in range(len(component_matrix)):
        cor_o = component_matrix[i]
        table.add_row()
        cur_row = table.rows[-1]
        cur_values = cor_o.get('values')  # dict类型
        cur_row.cells[0].text = cor_o.get('row_key')  # 填充第一列数据
        for j in cur_values.keys():
            # cur_row.cells[int(j) + 1].text = convert_str_to_float_3(cur_values.get(j))
            cur_j_value = cur_values.get(j)
            cur_j_value_str = convert_str_to_float_3(cur_values.get(j))
            run = cur_row.cells[int(j) + 1].paragraphs[0].add_run(cur_j_value_str)
            if cur_j_value and float(cur_j_value) >= 0.5:
                run.font.color.rgb = RGBColor(200, 0, 0)
        last_col_value = communalities[i].get('values').get('0')
        cur_row.cells[init_cols - 1].text = convert_str_to_float_3(last_col_value)  # 填充最后一列数据
    describe = ("本研究数据使用最大方差旋转方法（varimax)进行旋转，以便找出因子和研究项的对应关系。上表格展示因子对于研究项的信息提取情况，"
                "以及因子和研究项对应关系，从上表可知：所有研究项对应的共同度值均高于 0.4，且相应的因子载荷系数绝对值大于 0.5，意味着研究项"
                "和因子之间有着较强的关联性，因子可以有效的提取出信息。因此，量表具有良好的结构效度。")
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    paragraph.add_run(describe)
    # 格式化表格
    format_table(table)
    add_three_lines_table_va_table3(table)
    return


def add_three_lines_table_va_table3(table):
    delete_table_first_last_row(table)
    first_row = table.rows[0]
    second_row = table.rows[3]
    for cell in first_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, top={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def co_report(co_arr, document, describe_res):
    title1 = document.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('相关分析')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)
    # 增加描述1
    describe1 = ("在统计学中，研究一个问题的过程，通常都是从单变量的分析开始的，进一步分析双变量之间的关系，也有可能涉及到分析多变量之间的"
                 "关系。相关分析作为一种测度事物间统计关系强弱的手段和工具，旨在衡量变量之间线性相关程度的强弱。在相关分析重点研究两个变量"
                 "直接线性相关关系的强度和方向，在相关分析中，两个变量均为结果变量，不分主次。同时，一般用相关系数R来描述变量之间的线性相"
                 "关程度，相关系数R的正负值表示两个变量直接的线性相关的方向，R>0为正相关，R<0为负相关，R=0为零相关。R的绝对值则表示两变量"
                 "之间的线性相关的密切程度，R的绝对值越接近与1，说明密切程度越高；R的绝对值越接近于0，说明密切程度越低。Pearson相关系数，"
                 "也称积差相关系数，是定量地描述线性相关程度好坏的一个常用指标。")
    paragraph = document.add_paragraph()  # 插入段落
    paragraph.add_run(describe1)

    # 增加表格及描述2
    dynamic_col = len(co_arr)
    init_rows = 2
    init_cols = 3 + dynamic_col
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(document, init_rows, init_cols)
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + "Pearson相关"
    # 所有表头
    table.cell(1, 1).text = "平均值"
    table.cell(1, 2).text = "标准差"
    option_arr = []
    for i in range(len(co_arr)):
        cur_o = co_arr[i]
        fill_value = str(cur_o.get('row_key'))
        option_arr.append(fill_value)
        table.cell(1, 3 + i).text = fill_value
        # table.cell(2 + i, 0).text = fill_value
    for i in range(len(co_arr)):
        cur_o = co_arr[i]
        fill_value = str(cur_o.get('row_key'))
        table.add_row()
        cur_row = table.rows[-1]
        describe_obj = describe_res.get(fill_value)
        cur_row.cells[0].text = fill_value  # 填充第一列数据
        if describe_obj:
            cur_row.cells[1].text = convert_str_to_float_3(describe_obj.avg_value)  # 填充第一列数据
            cur_row.cells[2].text = convert_str_to_float_3(describe_obj.std_value)  # 填充第2列数据
        cur_values = cur_o.get('values')
        keys = list(cur_values.keys())
        for j in range(len(keys)):
            if int(j) <= i:
                cur_row.cells[3 + int(j)].text = cur_values.get(keys[j])
    # 动态添加数据
    describe = "利用相关分析去研究"
    for x in range(len(option_arr)):
        describe += option_arr[x]
        if x != len(option_arr) - 1:
            describe += '，'
    describe += f"共{len(option_arr)}项之间的相关关系，使用Pearson相关系数去表示相关关系的强弱情况。具体分析可知："
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    paragraph.add_run(describe)
    # 格式化表格
    format_table(table)
    add_three_lines_table_co(table)
    return


def add_three_lines_table_co(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[1]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, bottom={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def regressive_report(regressive_obj, document, table_count):
    title1 = document.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('回归分析')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)

    for i in range(len(regressive_obj)):
        item = regressive_obj[i]
        coefficients = item.get('coefficients')
        summary = item.get('summary')
        # 新建表格
        init_rows = 3
        init_cols = 7
        # table = document.add_table(rows=init_rows, cols=init_cols)
        table = create_table(document, init_rows, init_cols)
        # 填充第一行表头
        row = table.rows[0]  # 表格
        f_cell = None
        for i in range(init_cols):  # 合并单元格
            if i == 0:
                f_cell = table.cell(0, 0)
            else:
                f_cell.merge(table.cell(0, i))
        frequency_table_name = ""
        row.cells[0].text = frequency_table_name + "线性回归结果"
        table.cell(1, 0).merge(table.cell(2, 0))
        table.cell(1, 0).text = "模型" + str(i + 1)
        table.cell(1, 1).text = "未标准化系数"
        table.cell(2, 1).text = "B"
        table.cell(1, 2).merge(table.cell(2, 2))
        table.cell(1, 2).text = "标准错误"
        table.cell(1, 3).text = "标准化系数"
        table.cell(2, 3).text = "Beta"
        table.cell(1, 4).merge(table.cell(2, 4))
        table.cell(1, 4).text = "t"
        table.cell(1, 5).merge(table.cell(2, 5))
        table.cell(1, 5).text = "p"
        table.cell(1, 6).merge(table.cell(2, 6))
        table.cell(1, 6).text = "VIF"
        names = []
        for j in coefficients:
            table.add_row()
            cur_row = table.rows[-1]
            names.append(j.get('row_key'))
            cur_row.cells[0].text = j.get('row_key')
            cur_row.cells[1].text = convert_str_to_float_3(j.get('values').get('B'))
            cur_row.cells[2].text = convert_str_to_float_3(j.get('values').get('标准错误'))
            # cur_row.cells[3].text = j.get('values').get('B')
            cur_row.cells[4].text = convert_str_to_float_3(j.get('values').get('t'))
            cur_row.cells[5].text = convert_str_to_float_3(j.get('values').get('显著性'))
            cur_row.cells[6].text = convert_str_to_float_3(j.get('values').get('vif'))
        # 增加最后三排的数据
        table.add_row()
        cur_row = table.rows[-1]
        cur_row.cells[0].text = "R2"
        cur_row.cells[1].merge(cur_row.cells[2]).merge(cur_row.cells[3]).merge(cur_row.cells[4]).merge(
            cur_row.cells[5]).merge(cur_row.cells[6])
        cur_row.cells[1].text = convert_str_to_float_3(summary.get('rf'))

        table.add_row()
        cur_row = table.rows[-1]
        cur_row.cells[0].text = "调整后 R2"
        cur_row.cells[1].merge(cur_row.cells[2]).merge(cur_row.cells[3]).merge(cur_row.cells[4]).merge(
            cur_row.cells[5]).merge(cur_row.cells[6])
        adj_r2 = convert_str_to_float_3(summary.get('rf_adj'))
        cur_row.cells[1].text = adj_r2

        table.add_row()
        cur_row = table.rows[-1]
        cur_row.cells[0].text = "F"
        cur_row.cells[1].merge(cur_row.cells[2]).merge(cur_row.cells[3]).merge(cur_row.cells[4]).merge(
            cur_row.cells[5]).merge(cur_row.cells[6])
        fvalue = convert_str_to_float_3(summary.get('fvalue'))
        cur_row.cells[1].text = fvalue

        y = item.get('y')
        table.add_row()
        cur_row = table.rows[-1]
        cur_row.cells[0].text = "因变量"
        cur_row.cells[1].merge(cur_row.cells[2]).merge(cur_row.cells[3]).merge(cur_row.cells[4]).merge(
            cur_row.cells[5]).merge(cur_row.cells[6])
        cur_row.cells[1].text = str(y)

        # 格式化表格
        format_table(table)
        add_three_lines_table_regressive(table)
        # 插入描述信息
        paragraph = document.add_paragraph()  # 插入段落
        # 添加文本内容，并设置字体为黑体，字号为5号
        x_arr = item.get('x_arr')
        x_arr_str = ', '.join(x_arr)
        describe = (
            f"本研究采用层次回归法检验{x_arr_str}对{y}的影响，将{x_arr_str}作为自变量,{y}作为因变量，得到上表的回归结果。"
            f"由表可知，回归方程中各个自变量的VIF值在1.5左右，介于1—10之间，说明因变量与各自变量之间不存在严重的多重共线性问题。"
            f"模型的调整后的R2为{adj_r2}，"
            f"说明自变量{x_arr_str}可以解释因变量{y}：{convert_str_to_float_3_persent(summary.get('rf_adj'))}%的变异。"
            f"此外，模型的F值为{fvalue}（p＜0.001），说明模型的拟合度良好。"
            f"")
        paragraph.add_run(describe)
    return


def add_three_lines_table_regressive(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[3]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, top={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def add_three_lines_table(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[3]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, top={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def re_report(document, reliability_analysis_obj, table_count):
    title1 = document.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('信度分析')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)
    # 添加文本内容，并设置字体为黑体，字号为5号
    p1 = ("克朗巴赫系数（Cronbach alpha）是检验问卷信度的指标，广泛应用于实证数据的分析。一般来说，当问卷设计的量表的Cronbach alpha值低于"
          "0.7时，意味着该量表各变量的内部一致性较差，需要重新编制该量表；当量表的Cronbach alpha值高于0.7时，意味着量表构建的几个变量的内"
          "部一致性是好的；如果量表的Cronbach alpha值高于0.9，这意味着量表设计的变量的内部一致性是优秀的。")
    p2 = ("此外，本研究采用校正项目-总相关（CITC）来衡量单个问题项目的可靠性。在研究中，当满足以下两个条件时，应删除一个问题项：（1）一个问题"
          "项的总体相关系数CITC小于0.4；（2）删除问题项后量表的Cronbach alpha系数大于相应维度的Cronbach alpha系数的值。")
    p3 = "可靠性分析的结果如下表所示。"
    document.add_paragraph(p1)  # 插入段落
    document.add_paragraph(p2)  # 插入段落
    document.add_paragraph(p3)  # 插入段落
    # 新建表格
    init_rows = 2
    init_cols = 5
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(document, init_rows, init_cols)
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + '可靠性分析'
    # 填充第二行表头
    table.rows[1].cells[1].text = '项'
    table.rows[1].cells[2].text = '修正后的项与总计相关性'
    table.rows[1].cells[3].text = '删除项后的克隆巴赫 Alpha'
    table.rows[1].cells[4].text = '克隆巴赫 Alpha'
    itemize = reliability_analysis_obj.get('itemize')  # 每一个分维度的数组
    # 初始化描述信息
    describe = "结果表明，"
    # 处理动态生成的表格内容
    for i in itemize:
        # 获取一组的数据
        total_list = i.get('total')
        group_name = i.get('group_name')
        total_obj = total_list[0]
        # col1_text = total_obj.get('row_key')
        std_alpha = total_obj.get('values').get('std.alpha')
        # 获取每一行的数据
        alpha_drop = i.get('alpha_drop')
        item_status = i.get('item_status')
        first_cell = None  # 第一列需要合并
        last_cell = None  # 最后一列需要合并
        for j in range(len(alpha_drop)):
            table.add_row()  # 表格动态增加一行
            cur_row = table.rows[-1]
            if j == 0:
                # 处理表格
                first_text = group_name
                last_text = convert_str_to_float_3(std_alpha)
                # last_text = "{:.3f}".format(float(std_alpha))
                cur_row.cells[0].text = first_text
                cur_row.cells[init_cols - 1].text = last_text
                first_cell = cur_row.cells[0]
                last_cell = cur_row.cells[init_cols - 1]
                # 处理数据
                describe += first_text + "变量对应的Cronbach alpha系数值为"
                describe += last_text
                describe += "，"
            else:
                first_cell.merge(cur_row.cells[0])
                last_cell.merge(cur_row.cells[init_cols - 1])
            # 操作表格
            cur_row.cells[1].text = alpha_drop[j].get('row_key')
            cur_row.cells[2].text = "{:.3f}".format(float(item_status[j].get('values').get('r.drop')))
            cur_row.cells[3].text = "{:.3f}".format(float(alpha_drop[j].get('values').get('std.alpha')))

    # 格式化表格
    format_table(table)
    add_three_lines_table_re(table)
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    describe += ("各变量的Cronbach alpha系数值均大于0.7，同时各项目的CITC值和已删除项目的Cronbach alpha值均满足研究要求，"
                 "说明问卷中各变量的稳定性较高，信度基本通过检验。")
    paragraph.add_run(describe)
    return


def add_three_lines_table_re(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[1]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, bottom={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def frequency_report(document, frequency_obj, table_count):
    # 在 Word 文档中添加一个标题
    title1 = document.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('频数分析')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)
    # document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet')
    # document.add_page_break()  # 跳转到下一页
    # paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    # run = paragraph.add_run("这是黑体5号的文本")
    # run.font.name = r"黑体"
    # run.font.size = Pt(10.5)
    # prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum')  # 在某个段落之前插入段落
    # table = document.add_table(rows=2, cols=4)  # 频数分析模版1默认是1行4列的数据
    table = create_table(document, 2, 4)
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(4):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + '频数统计结果'
    table.rows[1].cells[0].text = '名称'
    table.rows[1].cells[1].text = '选项'
    table.rows[1].cells[2].text = '频数'
    table.rows[1].cells[3].text = '百分比%'
    frequency_describe = "频数分析用于研究定类数据的分布情况，选择频数和百分比分别是多少。由" + frequency_table_name + "可知："
    # 填充频数表格的数据，文档数据
    for i in frequency_obj:
        title = i.get('title')
        datas = i.get('datas')
        if not datas:
            continue
        first_cell = None
        max_option_str = ""
        min_option_str = ""
        for j in range(len(datas)):
            table.add_row()  # 表格动态增加一行
            cur_row = table.rows[-1]
            option_name = str(datas[j].get('values').get('选项'))
            count_str = str(int(datas[j].get('values').get('频数')))
            persent_str = "{:.3f}".format(float(datas[j].get('values').get('百分比(%)')) * 100)  # 保留3位小数，不满3位补0
            if j == 0:
                # 处理表格
                cur_row.cells[0].text = title
                first_cell = cur_row.cells[0]
                # 处理正文
                frequency_describe += "由" + title + "频数分析结果显示："
                max_option_str = option_name
            else:
                first_cell.merge(cur_row.cells[0])
                if j == len(datas) - 1:
                    min_option_str = option_name
            # 操作表格
            cur_row.cells[1].text = option_name
            cur_row.cells[2].text = count_str
            cur_row.cells[3].text = persent_str
            # 操作正文内容
            frequency_describe += option_name
            frequency_describe += "频数为"
            frequency_describe += count_str
            frequency_describe += "，所占百分比"
            frequency_describe += persent_str
            frequency_describe += "%；"
        frequency_describe += "其中"
        frequency_describe += max_option_str
        frequency_describe += "最高，"
        frequency_describe += min_option_str
        frequency_describe += "最低。"
    # 格式化表格
    format_table(table)
    add_three_lines_table(table)
    table_count += 1
    paragraph = document.add_paragraph()  # 插入段落
    # 添加文本内容，并设置字体为黑体，字号为5号
    paragraph.add_run(frequency_describe)
    # document.styles['Normal'].font.size = Pt(10.5)


def add_three_lines_table(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[1]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, bottom={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def format_table(table):
    # 遍历表格中的每个单元格设置对齐方式 - 全部水平居中
    for row in table.rows:
        for cell in row.cells:
            cell.height = 1
            for paragraph in cell.paragraphs:
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    table.alignment = WD_TABLE_ALIGNMENT.CENTER


def convert_str_to_float_3_persent(value) -> str:
    if not value:
        return ''
    if isinstance(value, str):
        return convert_str_to_float_3(float(value) * 100)
    return convert_str_to_float_3(float(value) * 100)


def convert_str_to_float_3(value) -> str:
    if not value:
        return ''
    if isinstance(value, str):
        return "{:.3f}".format(float(value))
    elif isinstance(value, float):
        return "{:.3f}".format(value)
    return "{:.3f}".format(value)


if __name__ == '__main__':
    # 创建 Document 对象，等价于在电脑上打开一个 Word 文档
    doc = Document()
    with open('mook_data.json', 'r') as file:
        # 解析JSON数据
        src_data = json.load(file)
    generate_report(src_data, doc, 1)  # 生成表格
    # 保存文档
    doc.save('demo.docx')
